function Analyze(subjectselector)
% ANALYZE Start analyses of all subjects

if ~exist('subjectselector', 'var'), subjectselector = {'CW'}; end
%if ~exist('subjectselector', 'var'), subjectselector = {'CW', 'DJ', 'DS', 'JF', 'FG', 'RV'}; end



% DeleteAllSubjectInfo();
% ResetTasks({'analyzeVisualResponsivenessBanded_Calculate'});
files = {};

if any(strcmp(subjectselector,'CW'))
    ProcessSubject('Subject CW', 'D:\Ralph\ECoG\diaryCW.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryCW.txt';
end

if any(strcmp(subjectselector,'DJ'))
    ProcessSubject('Subject DJ', 'D:\Ralph\ECoG\diaryDJ.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryDJ.txt';
end

if any(strcmp(subjectselector,'DS'))
    ProcessSubject('Subject DS', 'D:\Ralph\ECoG\diaryDS.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryDS.txt';
end

if any(strcmp(subjectselector,'JF'))
    ProcessSubject('Subject JF', 'D:\Ralph\ECoG\diaryJF.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryJF.txt';
end

if any(strcmp(subjectselector,'FG'))
    ProcessSubject('Subject FG', 'D:\Ralph\ECoG\diaryFG.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryFG.txt';
end

if any(strcmp(subjectselector,'RV'))
    ProcessSubject('Subject RV', 'D:\Ralph\ECoG\diaryRV.txt');
    files{end+1} = 'D:\Ralph\ECoG\diaryRV.txt';
end


setpref('Internet','SMTP_Server','smtp.uu.nl');
setpref('Internet','E_mail','r.j.m.hendriks@uu.nl');
% sendmail({'ralph@affy.nl','r.j.m.hendriks@uu.nl'},'Matlab diary','See attachement for transscript', files);
sendmail({'ralph@affy.nl','r.j.m.hendriks@uu.nl','dejongmc@gmail.com'},'Matlab diary','See attachement for transscript', files);


end

function DeleteAllSubjectInfo()
for x = SubjectInfo.List()
    SubjectInfo.Delete(cell2mat(x));
end
clear
end

% function ResetTasks(tasklist)
% for x = SubjectInfo.List()
%     subjectinfo = SubjectInfo.Load(cell2mat(x));
%     for t = tasklist
%         myTaskIndex = TaskInfo.FindTask(subjectinfo, cell2mat(t));
%         subjectinfo.Tasks(myTaskIndex) = subjectinfo.Tasks(myTaskIndex).SetToDo;
%         disp(['Task "' cell2mat(t) '" reset.']);
%     end
%     subjectinfo.Save
% end
% end

function ProcessSubject(subjectName, diaryFilename)
diary off
try
    delete(diaryFilename);
catch ME
    disp(ME)
end
diary(diaryFilename);
% try
    subjectinfo = CreateOrLoadSubject(subjectName);
    subjectinfo = AnalyzeSubject(subjectinfo);
    subjectinfo.Save();
% catch ME
%     disp('================================== Error');
%     disp(['message: ' ME.message])
%     disp('stack:')
%     for i = 1:length(ME.stack)
%         disp(ME.stack(i))
%     end
    %     % Saving in catch isn't wise, since subjectinfo is never returned from
    %     % the stack..
    % %     disp('================================== Saving SubjectInfo in catch..');
    % %     subjectinfo.Save();
% end
disp(subjectinfo);
pause(2);
diary off
end

function [subjectinfo] = AnalyzeSubject(subjectinfo)
clc
disp('Clearing the timer...');
tStart = tic;
disp(['Analyzing subject ' subjectinfo.PrimaryPrefix]);

%% Prepare the raw data
% [output1 subjectinfo] = prepareDatasets(subjectinfo, []);
% elapsedTime = round(toc(tStart) / 60);
% disp(['Time spent: ' num2str(elapsedTime) 's']);

%% Analyze Visual Responsiveness
% subjectinfo = analyzeVisualResponsiveness_PrepareSets(subjectinfo);
% subjectinfo = analyzeVisualResponsivenessFull_Calculate(subjectinfo);
% subjectinfo = analyzeVisualResponsivenessFull_PublishResults(subjectinfo);
% subjectinfo = analyzeVisualResponsivenessBanded_Calculate(subjectinfo);
% subjectinfo = analyzeVisualResponsivenessBanded_PublishResults(subjectinfo);
% elapsedTime = round(toc(tStart) / 60);
% disp(['Time spent: ' num2str(elapsedTime) 's']);

%% Build Epochs
cfgBE = buildEpochs_defaultCfg();
[outputBE subjectinfo] = buildEpochs(subjectinfo, cfgBE);
elapsedTime = round(toc(tStart) / 60);
disp(['Time spent: ' num2str(elapsedTime) ' min(s)']);

%% Create the ERSP plots
% cfgCE = createErsp_defaultCfg();
% switch subjectinfo.Name
%     case 'Subject CW'
% %       cfgCE.channels = {'T02' 'T03' 'T04' 'T05' 'T06' 'T07' 'T08' 'T09' 'T11' 'T12' 'T13' 'T14' 'T16' 'T17' 'T18' 'T19' 'T20' 'T21' 'T22' 'T23' 'T24' 'T25' 'T26' 'T30' 'T31' 'T32' 'sTa1' 'sTa3' 'sTa4' 'sTa5' 'sTa6' 'sTa7' 'sTa8' 'P03' 'P05' 'P06' 'P07' 'P08' 'P10' 'P11' 'P12' 'P13' 'P14' 'P15' 'P16' 'OcO1' 'OcO2' 'OcO3' 'OcO4' 'OcO5' 'OcO6' 'OcO7' 'OcO8' 'OcO9' 'Oc10' 'Oc11' 'Oc12' 'Oc13' 'Oc14' 'Oc15' 'Oc16'};
%         cfgCE.channels = {'T20' 'T21' 'T22' 'T23' 'T32' 'T18' 'T19' 'T26' 'T27' 'T28' 'T29' 'T30' 'T31' 'vT1' 'vT2' 'vT3' 'vT4' 'vT5' 'vT6' 'vT7' 'vT8' 'aT1' 'aT2' 'aT3' 'aT4' 'aT5' 'aT6' 'aT7' 'aT8' 'sTv1' 'sTv2' 'sTv3' 'sTv4' 'sTv5' 'sTv6' 'sTv7' 'sTv8' 'sTa1' 'sTa2' 'sTa3' 'sTa4' 'sTa5' 'sTa6' 'sTa7' 'sTa8' 'OcO7' 'OcO8' 'Oc15' 'Oc16'};
%     case 'Subject DJ'
% %       cfgCE.channels = {'sO1' 'sO2' 'sO3' 'sO4' 'sO5' 'sO6' 'sO7' 'sO8' 'Oc01' 'Oc02' 'Oc04' 'Oc05' 'Oc07' 'Oc08' 'Oc09' 'Oc10' 'Oc11' 'Oc12' 'Oc13' 'Oc14' 'Oc15' 'Oc16' 'C01' 'C02' 'C03' 'C04' 'C05' 'C06' 'C07' 'C08' 'OL03' 'OL06' 'OL07' 'OL08' 'OL11' 'OL15' 'OL16' 'PO1' 'PO2' 'PO3' 'PO4' 'PO5' 'PO6' 'PO7' 'PO8' 'PO9' 'PO10' 'PO11' 'PO12' 'PO13' 'PO14' 'PO15' 'PO16' 'TO01' 'TO02' 'TO03' 'TO04' 'TO05' 'TO06' 'TO09' 'TO10' 'TO12' 'TO13' 'TO14' 'TO16' };
%         cfgCE.channels = {'T01' 'T02' 'T03' 'T04' 'T05' 'T06' 'T07' 'T08' 'T09' 'T10' 'T11' 'T12' 'T13' 'T14' 'T15' 'T16' 'T17' 'T18' 'T19' 'T20' 'T21' 'T22' 'T23' 'T24' 'T25' 'T26' 'T27' 'T28' 'T29' 'T30' 'T31' 'T32' 'sT1' 'sT2' 'sT3' 'sT4' 'sT5' 'sT6' 'sT7' 'sT8'};
%     case 'Subject FG'
%         cfgCE.channels = {'C01' 'C02' 'C03' 'C04' 'C05' 'C06' 'C07' 'C08' 'P01' 'P02' 'P03' 'P04' 'P05' 'P06' 'P07' 'P08' 'P09' 'P10' 'P11' 'P12' 'P13' 'P14' 'P15' 'P16' 'P17' 'P18' 'P19' 'P20' 'P21' 'P22' 'P23' 'P24' 'P25' 'P26' 'P27' 'P28' 'P29' 'P30' 'P31' 'P32' 'T01' 'T02' 'T03' 'T09' 'T10' 'T14' 'T17' 'T18' 'IP1' 'IP2' 'IP3' 'IP4' 'IP5' 'IP6' 'IP7' 'IP8' 'IP9' 'IP10' 'IP11' 'IP12' 'IP13' 'IP14' 'IP15' 'IP16' 'F02' 'ST6' 'ST7' 'ST8'};
%     case 'Subject JF'
% %       cfgCE.channels = {'TO2' 'TO4' 'TO5' 'TO6' 'TO7' 'TO8' 'TO10' 'TO12' 'TO13' 'TO14' 'TO15' 'TO16' 'TO17' 'TO18' 'TO19' 'TO22' 'TO23' 'TO24' 'TO26' 'TO30' 'TO31' 'TO32' 'TO34' 'TO36' 'TO37' 'TO38' 'TO39' 'TO40' 'TO41' 'TO42' 'TO43' 'TO46' 'TO47' 'TO48' 'P01' 'P06' 'P07' 'P08' 'P09' 'P10' 'P11' 'P12' 'P13' 'P14' 'P16'};
%         cfgCE.channels = {'TO4' 'TO5' 'TO6' 'TO7' 'TO12' 'TO13' 'TO14' 'TO24' 'TO31' 'TO32' 'TO8' 'TO15' 'TO16' 'TO22' 'TO23' 'TO30' 'ST1' 'ST2' 'ST3' 'ST4' 'ST5' 'ST6' 'ST7' 'ST8' 'VT1' 'VT2' 'VT3' 'VT4' 'VT5' 'VT6' 'VT7' 'VT8'};
%     case 'Subject RV'
%         cfgCE.channels = {'C01' 'C26' 'C30' 'C33' 'C41' 'C42' 'C43' 'C44' 'C45' 'C46' 'C50' 'C54' 'C55' 'C57' 'C58' 'C62' 'C63' 'C64' 'T01' 'T02' 'T03' 'T05' 'T06' 'T07' 'T08' 'IH1' 'IH2' 'IH3' 'IH4' 'IH5' 'IH6' 'IH7' 'IH8' 'IH9' 'IH10' 'IH11' 'IH12' 'IH13' 'IH14' 'IH15' 'IH16'};
% end
% cfgCE.epochSets = { ...
%     'FaceHouseAmbiguousResponse' ...
%     'FaceHouseAmbiguousFaceResponses' ...
%     'FaceHouseAmbiguousHouseResponses' ...
%     'FaceHouseUnambiguousResponse' ...
%     'FaceHouseUnambiguousFaceResponse' ...
%     'FaceHouseUnambiguousHouseResponse' ...
%     'FaceHouseUnambiguousStimulus' ...
%     'FaceHouseUnambiguousFaceStimulus' ...
%     'FaceHouseUnambiguousHouseStimulus' ...
%     };
% %     'SphereAmbiguousResponse'  ...
% %     'SphereUnambiguousResponse' ...
% %     'SphereUnambiguousStimulus' ...
% %     'SphereVoluntaryStimulus' ...
% %     'SphereVoluntaryWantedResponse' ...
% %     'SphereVoluntaryUnwantedResponse' ...
% [outputCE subjectinfo] = createErsp(subjectinfo, cfgCE);
% elapsedTime = round(toc(tStart) / 60);
% disp(['Time spent: ' num2str(elapsedTime) ' min(s)']);

%% Build Frequency Set
% To use the channels defined as useful in dec2010/jan2011, load the
% TFData.mat and extract the info from there..
load('D:\Ralph\ECoG Code\TimeFrequency\TFData.mat')
SelectedElectrodes = [];
for sI = 2:length(regions_header)
    subject = regions_header{sI};
    SelectedElectrodes.(subject) = {};
end
for rI = 1:size(regions,1)
    channel = regions{rI, strcmp(regions_header, 'Region')};
    for sI = 2:length(regions_header)
        subject = regions_header{sI};
        sources = regions{rI, sI};
        SelectedElectrodes.(subject) = [SelectedElectrodes.(subject) sources];
%         if isempty(sources)
%             sourceText = 'N/A';
%         else
%             sourceText = sources{1};
%             for t = 2:length(sources), sourceText = [sourceText ', ' sources{t}]; end
%         end
%         disp([channel ' in subject ' subject ': ' sourceText]);
    end
end
for sI = 2:length(regions_header)
    subject = regions_header{sI};
    SelectedElectrodes.(subject) = sort(unique(SelectedElectrodes.(subject)));
end



load('Electrodes.mat');
cfgBFS = buildFrequencySet_defaultCfg();
switch subjectinfo.Name
    case 'Subject CW'
        cfgBFS.ProcessAllChannels = false;
%         cw = Electrodes.CW;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%             cw.P11, cw.P12, ... % IPSSLob
%             cw.P05, cw.P13, ... % IPSSips
%             cw.P14, cw.P06, ... % IPSIips
%             cw.P16, cw.T01, ... % IPSIang
%             cw.T02, cw.T03, cw.T04, cw.T05, cw.P15, cw.P16, cw.P07, cw.P08, ... % IPSIsup
%             cw.OcO9, cw.Oc10, cw.Oc11, cw.sTa1, cw.sTa2, ... % OCCpole
%             cw.Oc12, cw.Oc13, cw.OcO1, cw.OcO2, cw.OcO3, cw.OcO4, cw.sTa3, ... % OCCextr
%             cw.T09, cw.T17, cw.OcO5, ... % PAROlat
%             ... % PAROmed
%             cw.P01, cw.P02, cw.P09, ... % motor
%             cw.T11, cw.T18, cw.T19, cw.T20, cw.T21, ... % TEMang
%             cw.T25, cw.T26, ... % extra
%             cw.sTa1, cw.sTa2, cw.sTa3, cw.sTa4, cw.sTa5, cw.sTa6, cw.sTa7, cw.sTv3, cw.sTv4, cw.sTv5, cw.sTv6, cw.aT1, cw.aT2, cw.aT3, cw.aT4, cw.aT5, cw.aT6, cw.aT7, ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.CW;
    case 'Subject DJ'
        cfgBFS.ProcessAllChannels = false;
%         dj = Electrodes.DJ;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%             dj.OL15, dj.OL16, dj.OL08, dj.OL07, dj.OL06, dj.PO15, ... % IPSSLob
%             dj.PO13, dj.PO14, dj.PO7, ... % IPSSips
%             dj.TO07, dj.TO14, dj.TO15, dj.PO5, dj.PO6, ... % IPSIips
%             dj.TO11, dj.TO12, dj.PO4, dj.TO04, ... % IPSIang
%             dj.T08, dj.TO05, dj.TO06, dj.TO13, ... % IPSIsup
%             dj.OL01, dj.OL09, dj.Oc16, dj.sO1, ... % OCCpole
%             dj.sO2, dj.sO3, dj.sO4, dj.sO5, dj.sO6, dj.sO7, dj.sO8, dj.PO1, dj.PO9, dj.PO10, dj.TO09, dj.Oc08, dj.OL02, dj.OL03, dj.OL10, dj.OL11, ... % OCCextr
%             dj.PO3, dj.PO11, dj.OL05 ... % PAROlat
%             dj.OL12, dj.OL13, dj.OL14, dj.OL04, ... % PAROmed
%             dj.T04, dj.T05, ... % motor
%             dj.T24, dj.TO03, ... % TEMang
%             ... % extra
%             dj.sT4, dj.sT5, dj.sT6 ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.DJ;
    case 'Subject DS'
        cfgBFS.ProcessAllChannels = false;
%         ds = Electrodes.DS;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%             ds.P41, ds.P42, ds.P43, ... % IPSSLob
%             ds.P44, ds.P36, ... % IPSSips
%             ds.P45, ds.P37, ... % IPSIips
%             ds.Oc55, ... % IPSIang
%             ds.P46, ds.P47, ... % IPSIsup
%             ds.Oc49, ds.Oc50, ds.Oc57, ds.Oc58, ds.Oc59, ... % OCCpole
%             ds.Oc51, ds.Oc52, ds.Oc60, ds.Oc61, ds.Oc62, ds.Oc63, ... % OCCextr
%             ds.Oc53, ds.Oc54, ... % PAROlat
%             ... % PAROmed
%             ... % motor
%             ds.T23, ds.T24, ds.T15, ds.T16, ds.Oc56, ... % TEMang
%             ds.sTa5, ds.sTa1, ds.sTa2, ... % extra
%             ds.sTv1, ds.sTv4, ds.sTv6, ds.sTv7, ds.aT1, ds.aT5, ds.aT6, ds.sTa1, ds.sTa2, ds.sTa5, ds.sTa6, ds.T18 ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.DS;
    case 'Subject FG'
        cfgBFS.ProcessAllChannels = false;
%         fg = Electrodes.FG;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%              ... % IPSSLob
%              ... % IPSSips
%              ... % IPSIips
%              ... % IPSIang
%              ... % IPSIsup
%              ... % OCCpole
%              ... % OCCextr
%              ... % PAROlat
%              ... % PAROmed
%              ... % motor
%              ... % TEMang
%              ... % extra
%              ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.FG;
    case 'Subject JF'
        cfgBFS.ProcessAllChannels = false;
%         jf = Electrodes.JF;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%             jf.P07, jf.P09, jf.P11, ... % IPSSLob
%             jf.P03, jf.P05, ... % IPSSips
%             jf.P06, jf.P08, jf.P10, jf.P12, ... % IPSIips
%             jf.TO36, jf.TO37, jf.TO44, jf.TO45, ... % IPSIang
%             jf.TO39, jf.TO40, jf.TO46, jf.TO47, jf.TO48, ... % IPSIsup
%             jf.TO1, jf.TO9, ... % OCCpole
%             jf.TO2, jf.TO3, jf.TO10, jf.TO17, jf.TO18, jf.TO19, jf.TO25, jf.TO26, jf.TO33, jf.TO41, ... % OCCextr
%             jf.TO21, jf.TO27, jf.TO28, jf.TO29, jf.TO34, jf.TO35, jf.TO42, jf.TO43, ... % PAROlat
%             jf.P01, jf.P02, jf.P04, ... % PAROmed
%             ... % motor
%             jf.TO16, jf.TO24, jf.TO23, jf.TO22, jf.TO31, jf.TO30, ... % TEMang
%             ... % extra
%             ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.JF;
    case 'Subject RV'
        cfgBFS.ProcessAllChannels = false;
%         rv = Electrodes.RV;
%         cfgBFS.ChannelSelection = sort(unique({ ...
%             rv.C01, rv.C02, rv.C09, rv.C10, rv.C17, rv.C18, ... % IPSSLob
%             rv.C26, rv.C27, ... % IPSSips
%             rv.C25, rv.C41, rv.C42, rv.C43, ... % IPSIips
%             rv.C57, ... % IPSIang
%             rv.C49, rv.C50, rv.C51, rv.C58, rv.C59, ... % IPSIsup
%              ... % OCCpole
%              ... % OCCextr
%              ... % PAROlat
%              ... % PAROmed
%             rv.IH7, rv.IH8, rv.IH16, ... % motor
%              ... % TEMang
%             rv.T05, rv.T06, ... % extra
%             rv.T01, rv.T02, rv.T03, rv.T04, rv.T05, rv.T06 ... % FFA/PPA
%             }));
        cfgBFS.ChannelSelection = SelectedElectrodes.RV;
end
% [outputBFS subjectinfo] = buildFrequencySet(subjectinfo, cfgBFS);
fnames = fieldnames(subjectinfo.EpochData)';
% %     'SphereVoluntaryWantedResponse' ...
% %     'SphereVoluntaryUnwantedResponse' ...
for fn = fnames
    x = subjectinfo.EpochData.(cell2mat(fn));
    disp(x.name);
    cfgBFS.SubjectPrimaryPrefix = subjectinfo.PrimaryPrefix;
    cfgBFS.EpochSetName = x.name;
    cfgBFS.Input.EegSetFilename = x.dataFilename;
    cfgBFS.Output.TfcDataFolder = [getpref('ECoG','Data') 'Timefreq\'];
    outputBFS = buildFrequencySet_Core(cfgBFS);
    if ~isempty(outputBFS), subjectinfo.EpochData.(cell2mat(fn)).TfcData = outputBFS.TfcData; end
    elapsedTime = round(toc(tStart) / 60);
    disp(['Time spent: ' num2str(elapsedTime) ' min(s)']);
end

end

function [subjectinfo] = CreateOrLoadSubject(subjectName)
if SubjectInfo.Exist(subjectName)
    subjectinfo = SubjectInfo.Load(subjectName);
else
    switch subjectName
        case 'Subject CW'
            CreateSubjectCW;
        case 'Subject DJ'
            CreateSubjectDJ;
        case 'Subject FG'
            CreateSubjectFG;
        case 'Subject JF'
            CreateSubjectJF;
        case 'Subject RV'
            CreateSubjectRV;
        case 'Subject DS'
            CreateSubjectDS;
    end
    subjectinfo = s;
end
end
